package service

import (
	"fmt"
	"go.uber.org/zap"
	"iot-base/common/cache"
	"iot-base/common/ctrltype"
	"iot-base/common/logger"
	"iot-base/common/notify"
	"regexp"
	"strconv"
	"strings"
	"time"

	"errors"
)

type So2 struct {
	So2        float64 `json:"so2" msgpack:"so2"`       // so2
	Status     float64 `json:"status" msgpack:"Status"` // 状态
	PmtV       float64 `json:"pmt_v" msgpack:"Status"`  // PMT电压值
	CanbiV     float64 `json:"canbi_v"`                 // 参比光强
	Power      float64 `json:"power"`                   // 电源组件
	Press      float64 `json:"press"`                   // 样气压力
	Flow       float64 `json:"flow"`                    // 样气流量
	Temp       float64 `json:"temp"`                    // 反应室温度
	Boxtemp    float64 `json:"boxtemp"`                 // 机箱温度
	PmtHvdis   float64 `json:"pmt_hvdis"`               // 倍增管高压
	XiandengHv float64 `json:"xiandeng_hv"`             // 光源高压
}

// So2Field 上传字段
var So2Field = map[int]string{
	1: "pmt_v",
	2: "canbi_v",
	3: "power",
	4: "press",
	5: "flow",
	6: "temp",
	7: "boxtemp",
	8: "pmt_hvdis",
	9: "xiandeng_hv",
}

type So2Logic struct {
}

func NewSo2Logic() *So2Logic {
	return &So2Logic{}
}

// So2 氧化硫. 5200
func (this *So2Logic) So2(id string, thing *cache.ThingInfo, v interface{}, round int64) (interface{}, error) {
	ip := thing.GetThingParam("ip", "")
	port := thing.GetThingParam("port", "")
	so2Str, err := SynHub.SendStrData(ip+":"+port, "so2chr$")
	if err != nil {
		logger.Log.Error("So2 service.SynHub.SendStrData err:", zap.Error(err))
		return nil, err
	}
	if strings.Contains(so2Str, "error") {
		logger.Log.Error("So2 service.SynHub.SendStrData err:" + so2Str)
		fmt.Println("so2chr$", so2Str)
		return nil, err
	}
	logger.Log.Info("So2 so2chr$ " + so2Str)
	fmt.Println("so2chr$ info:=", so2Str, err)
	so2Arr := strings.Split(so2Str, "=")
	var status float64 = 1
	switch so2Arr[0][0:1] {
	case "*":
		status = 2
	case "#":
		status = 3
	}
	reg := regexp.MustCompile("[\\-]?[\\d]+\\.?[\\d]+")
	data := reg.Find([]byte(so2Arr[1]))
	now := time.Now().Unix()
	so2, _ := strconv.ParseFloat(string(data), 64)
	notify.RawData(thing.Thing.UID, "so2", "", 0, so2, now, now)
	notify.RawData(thing.Thing.UID, "status", "", 0, status, now, now)
	notify.RawData(thing.Thing.UID, "so2ValueStatus", "", 0, fmt.Sprintf("%s%v", so2Arr[0][0:1], so2), now, now)
	fmt.Println("上传数据", so2, status)
	so2twc, err := SynHub.SendStrData(ip+":"+port, "so2twc$")
	fmt.Println("so2twc", so2twc, err)
	if err != nil {
		logger.Log.Error("So2 service.SynHub.SendStrData err:", zap.Error(err))
		return nil, err
	}
	logger.Log.Info("So2 so2twc$ " + so2twc)
	if strings.Contains(so2Str, "error") {
		logger.Log.Error("So2 so2twc$ service.SynHub.SendStrData err:" + so2twc)
		fmt.Println("so2twc$", so2twc)
		return nil, err
	}
	// 上传状态.
	//373.0,---,2691.6,99.6,0.0,44.6,26.2,573.7,400.8$
	so2twc = so2twc[:len(so2twc)-1]
	so2twcArr := strings.Split(so2twc, ",")
	for k, v := range so2twcArr {
		if k == 1 {
			// 暂时没有, ---
			continue
		}
		value, _ := strconv.ParseFloat(v, 64)
		if field, ok := So2Field[k+1]; ok {
			notify.RawData(thing.Thing.UID, field, "", 0, value, now, now)
		}

	}
	return nil, nil
}

func (this *So2Logic) So2Sv(pCmd *ctrltype.CtrlCmd, tingInfo *cache.ThingInfo) (map[string]interface{}, error) {
	ip := tingInfo.GetThingParam("ip", "")
	port := tingInfo.GetThingParam("port", "")
	var requestMap map[string]interface{}
	requestMap = make(map[string]interface{})
	switch pCmd.ID {
	case "szeros":
		readbuffer, err := SynHub.SendStrData(ip+":"+port, "szeros$")
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if readbuffer == "szerosok$$" {
			requestMap["msg"] = "ok"
		} else {
			requestMap["msg"] = "fail:" + readbuffer
			return requestMap, errors.New("fail:" + readbuffer)
		}
		return requestMap, nil
	case "szeroe":
		readbuffer, err := SynHub.SendStrData(ip+":"+port, "szeroe$")
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "ok") {
			requestMap["msg"] = "ok"
		} else {
			requestMap["msg"] = "fail:" + readbuffer
			return requestMap, errors.New("fail:" + readbuffer)
		}
		return requestMap, nil
	case "szeroq":
		readbuffer, err := SynHub.SendStrData(ip+":"+port, "szeroq$")
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "ok") {
			requestMap["msg"] = "ok"
		} else {
			requestMap["msg"] = "fail:" + readbuffer
			return requestMap, errors.New("fail:" + readbuffer)
		}
		return requestMap, nil
	case "sspans":
		concentration, ok := pCmd.Params["concentration"].(string)
		if !ok {
			return nil, errors.New("concentration type is err")
		}
		if len(concentration) < 3 {
			for i := 0; i < 4-len(concentration); i++ {
				concentration = "0" + concentration
			}
		}
		readbuffer, err := SynHub.SendStrData(ip+":"+port, "sspans "+concentration+"$")
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "ok") {
			requestMap["msg"] = "ok"
		} else {
			requestMap["msg"] = "fail:" + readbuffer
			return requestMap, errors.New("fail:" + readbuffer)
		}
		return requestMap, nil
	case "sspane":
		concentration, ok := pCmd.Params["concentration"].(string)
		if !ok {
			return nil, errors.New("concentration type is err")
		}
		if len(concentration) < 3 {
			for i := 0; i < 4-len(concentration); i++ {
				concentration = "0" + concentration
			}
		}
		readbuffer, err := SynHub.SendStrData(ip+":"+port, "sspane "+concentration+"$")
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "ok") {
			requestMap["msg"] = "ok"
		} else {
			requestMap["msg"] = "fail:" + readbuffer
			return requestMap, errors.New("fail:" + readbuffer)
		}
		return requestMap, nil
	case "sspanq":
		concentration, ok := pCmd.Params["concentration"].(string)
		if !ok {
			return nil, errors.New("concentration type is err")
		}
		if len(concentration) < 3 {
			for i := 0; i < 4-len(concentration); i++ {
				concentration = "0" + concentration
			}
		}
		readbuffer, err := SynHub.SendStrData(ip+":"+port, "sspanq "+concentration+"$")
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "ok") {
			requestMap["msg"] = "ok"
		} else {
			requestMap["msg"] = "fail:" + readbuffer
			return requestMap, errors.New("fail:" + readbuffer)
		}
		return requestMap, nil
	case "status":
		readbuffer, err := SynHub.SendStrData(ip+":"+port, "so2chr$")
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "error") {
			logger.Log.Error("so2 service.SynHub.SendStrData err:" + readbuffer)
			fmt.Println("so2chr$", readbuffer)
			return nil, err
		}
		logger.Log.Info("so2 so2chr$ info:=" + readbuffer)
		fmt.Println("so2chr$ info:=", readbuffer, err)
		if err != nil {
			logger.Log.Error("so2 service.SynHub.SendStrData err:", zap.Error(err))
			return nil, err
		}
		switch readbuffer[:1] {
		case "*":
			requestMap["msg"] = "2"
		case "#":
			requestMap["msg"] = "3"
		default:
			requestMap["msg"] = "1"
		}
		return requestMap, nil
	case "value":
		readbuffer, err := SynHub.SendStrData(ip+":"+port, "so2chr$")
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "error") {
			logger.Log.Error("so2 service.SynHub.SendStrData err:" + readbuffer)
			fmt.Println("so2chr$", readbuffer)
			return nil, err
		}
		logger.Log.Info("so2 so2chr$ info:=" + readbuffer)
		fmt.Println("so2chr$ info:=", readbuffer, err)
		if err != nil {
			logger.Log.Error("so2 service.SynHub.SendStrData err:", zap.Error(err))
			return nil, err
		}
		data := strings.Split(readbuffer, "=")
		if len(data) != 2 {
			return nil, errors.New("return data is err:" + readbuffer)
		}
		data[1] = strings.Replace(data[1], "$", "", -1)
		if data[1][0] == '*' || data[1][0] == '#' {
			requestMap["value"] = data[1][1:]
		} else {
			requestMap["value"] = data[1]
		}
		return requestMap, nil
	case "his":
		start, ok := pCmd.Params["start"].(string)
		if !ok {
			return nil, errors.New("start type is err")
		}
		end, ok := pCmd.Params["end"].(string)
		if !ok {
			return nil, errors.New("end type is err")
		}
		readbuffer, err := SynHub.SendStrData(ip+":"+port, "so2his"+start+" "+end+"$")
		if err != nil {
			return nil, errors.New("read err:" + err.Error())
		}
		if strings.Contains(readbuffer, "error") {
			logger.Log.Error("so2 service.SynHub.SendStrData err:" + readbuffer)
			fmt.Println("so2his", readbuffer)
			return nil, err
		}
		requestMap["result"] = readbuffer
		return requestMap, nil
	default:
		return nil, errors.New("no service")
	}

}
